package com.star.truffle.gateway;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

import java.net.URI;
import java.util.Arrays;
import java.util.List;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.util.UriComponentsBuilder;

public class RequestTimeGatewayFilterFactory extends AbstractGatewayFilterFactory<RequestTimeGatewayFilterFactory.Config> {

  private static final String KEY = "withParams";

  @Override
  public List<String> shortcutFieldOrder() {
    return Arrays.asList(KEY);
  }

  public RequestTimeGatewayFilterFactory() {
    super(Config.class);
  }

  @Override
  public GatewayFilter apply(Config config) {
    return (exchange, chain) -> {
      ServerHttpRequest request = exchange.getRequest();
      addOriginalRequestUrl(exchange, request.getURI());
      String newPath = "http://local.cnhnkj.cn:8082/api/getAreaByAreaId";
      URI uri = UriComponentsBuilder.fromHttpUrl(newPath).build().toUri();
      ServerHttpRequest newRequest = request.mutate().uri(uri).build();
      Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
      Route route2 = Route.async()
          .asyncPredicate(route.getPredicate())
          .filters(route.getFilters())
          .id("aaa")
          .order(route.getOrder())
          .uri("http://local.cnhnkj.cn:8082/api/getAreaByAreaId")
          .build();
      exchange.getAttributes().put(GATEWAY_ROUTE_ATTR, route2);
      
      return chain.filter(exchange.mutate().request(newRequest).build());
    };
  }

  public static class Config {

    private boolean withParams;

    public boolean isWithParams() {
      return withParams;
    }

    public void setWithParams(boolean withParams) {
      this.withParams = withParams;
    }

  }
}